package com.android.adapter;

import java.util.ArrayList;

import com.android.entity.Customer;
import com.android.wineshop.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;

public class Customer_Adapter extends ArrayAdapter<Customer> {
	TextView name;
	Filter filter;
	ArrayList<Customer> allItem;
	ArrayList<Customer> subItem;
	ArrayList<Customer> list;
	ArrayList<Customer> nList;
	public Customer_Adapter(Context context, int textViewResourceId,
			ArrayList<Customer> array_customer) {
		super(context, textViewResourceId, array_customer);
		this.allItem = new ArrayList<Customer>(array_customer);
		this.subItem = new ArrayList<Customer>(array_customer);
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent){
		View v = convertView;
		if(v == null){
			LayoutInflater in = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = in.inflate(R.layout.list_item, null);
		}
		Customer cust = getItem(position);
		if(cust != null){
			name = (TextView)v.findViewById(R.id.names);
			if(name != null){
				name.setText(cust.getCustomer_name().toString());
			}
		}
		return v;
		
	}
	@Override
	public Filter getFilter(){
		if(filter == null)
			filter = new CustomerFilter();
		return filter;
		
	}
	
	public class CustomerFilter extends Filter{

		@Override
		protected FilterResults performFiltering(CharSequence constraint) {
			FilterResults result = new FilterResults();
			String prefix = constraint.toString().toLowerCase();
			if(prefix == null || prefix.length() == 0){
				list = new ArrayList<Customer>(allItem);
				result.values = list;
				result.count = list.size();
			}
			else{
				list = allItem;
				int count = list.size();
				nList = new ArrayList<Customer>(count);
				for(int i = 0; i< count; i++){
					Customer customer = list.get(i);
					String name = customer.getCustomer_name().toLowerCase();
					if(name.contains(prefix)){
						nList.add(customer);
					}
				}
				result.values = nList;
				result.count = nList.size();
			}
			return result;
		}

		@SuppressWarnings("unchecked")
		@Override
		protected void publishResults(CharSequence constraint,
				FilterResults results) {
			subItem = (ArrayList<Customer>)results.values;
			clear();
			int count = subItem.size();
			for(int i  = 0 ; i< count ; i++){
				Customer cust = subItem.get(i);
				add(cust);
			}
			 if (subItem.size() > 0)
	                notifyDataSetChanged();
	            else
	                notifyDataSetInvalidated();
		}
		
	}

}
